package com.yzw.helloword;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.util.Timer;

/**
 * @Author: YangZhenWei
 * @PROJECT_NAME: nettyTeach
 * @DESCRIPTION: 客户端启动类
 * @USER: root
 * @DATE: 2023/2/8 22:51
 **/
public class AppClientHello {

    private final String host;
    private final int port;

    public AppClientHello(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();// io线程池
        try {
            Bootstrap bs = new Bootstrap();
            bs.group(group)
                    .channel(NioSocketChannel.class) // 实例化一个通道
                    .remoteAddress(new InetSocketAddress(host, port)) // 指定远程的ip和端口
                    .handler(new ChannelInitializer<SocketChannel>() {// 进行通道的初始化配置
                        /**
                         * 初始化通道，添加通道的处理handler
                         *
                         * @param socketChannel 通道
                         * @throws Exception
                         */
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new HandlerClientHello());// 添加自定义的handler
                        }
                    });
            //链接获取异步操作的结果值，链接到远程节点，等待链接完成
            ChannelFuture future = bs.connect().sync();

            // 消息到服务器端，编码格式为utf-8
//            while (true){
//                Thread.sleep(1000);
//                future.channel().writeAndFlush(Unpooled.copiedBuffer("hello word", CharsetUtil.UTF_8));
//            }
            future.channel().writeAndFlush(Unpooled.copiedBuffer("hello word", CharsetUtil.UTF_8));
            // 阻塞操作，closeFuture()开启了一个Channel的监听器,这期间channel在进行各种操作,直到连接断开
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new AppClientHello("127.0.0.1",18080).run();
    }
}
